<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card class="box-card">
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="7">
          <div class="grid-content bg-purple">
            <el-input
              placeholder="请输入内容"
              v
              v-model="queryInfo.query"
              clearable
              @clear="searchUser"
            >
              <el-button
                slot="append"
                icon="el-icon-search"
                @click="searchUser"
              ></el-button>
            </el-input>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="grid-content bg-purple">
            <el-button type="primary" @click="addDialogVisible = true"
              >添加用户</el-button
            >
          </div>
        </el-col>
      </el-row>
      <!-- 表格内容 -->
      <el-table :data="userList" style="width: 100%" border sripe>
        <el-table-column type="index"> </el-table-column>
        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="userSateChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="修改"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="primary"
                size="mini"
                icon="el-icon-edit"
                circle
                @click="showEditDialog(scope.row.id)"
              ></el-button>
            </el-tooltip>
            <!-- 删除按钮 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="删除"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="danger"
                size="mini"
                icon="el-icon-delete"
                circle
                @click="removeUser(scope.row.id)"
              ></el-button>
            </el-tooltip>

            <!-- 分配角色按钮 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                size="mini"
                icon="el-icon-setting"
                circle
                 @click="setRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
      <!-- 添加用户对话框 -->
      <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="30%" @close="addDialogClosed">
        <!-- 内容主题区域 -->
        <el-form
          :model="AddForm"
          :rules="AddFormRules"
          ref="AddFormRef"
          label-width="70px"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="AddForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input type="password" v-model="AddForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="AddForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="AddForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="btnAddUser"
            >确 定</el-button
          >
        </span>
      </el-dialog>
      <!-- 修改用户信息对话框 -->
      <el-dialog
        title="修改用户"
        :visible.sync="editDialogVisible"
        width="50%"
        @close="editDialogClosed"
        >
         <!-- 内容主题区域 -->
        <el-form
          :model="editForm"
          :rules="editFormRules"
          ref="editFormRef"
          label-width="70px"
        >
          <el-form-item label="用户名">
            <el-input v-model="editForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="editForm.mobile"></el-input>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
            <el-button @click="editDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="btnEditUserInfo">确 定</el-button>
        </span>
       </el-dialog>
    </el-card>

     <!-- 分配角色对话框 -->
       
            <el-dialog
            title="分配角色"
            :visible.sync="setRoleDialogVisible"
            width="50%" @close="setRoleDialogClosed">
             <div>
                 <p>当前的用户:{{userInfoData.username}}</p>
                 <p>当前的角色：{{userInfoData.role_name}}</p>
                 <!-- {{roleValue}} -->
                <p>分配新角色:
                    <el-select v-model="roleValue" placeholder="请选择">
                        <el-option
                        v-for="item in rolesList"
                        :key="item.id"
                        :label="item.roleName"
                        :value="item.id">
                        </el-option>
                    </el-select>
                </p>
             </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="setRoleDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
            </span>
            </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
export default {
  data() {
    //   自定义检验规则
    // 验证邮箱
    var checkEamil=(rule,value,cb)=>{
        // 验证邮箱正则表达式
      const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
      if (mailReg.test(value)) {
        //   合法的邮箱
          return cb();
      }
      cb(new Error("请输入合法的邮箱"))
    } 
    // 验证手机
    var checkMobile=(rule,value,cb)=>{
       // 验证手机正则表达式
       const phoneReg =  /^1[3|4|5|7|8][0-9]{9}$/
       if (phoneReg.test(value)) {
        //   合法的手机
          return cb();
       }
       cb(new Error("请输入合法的手机号码"))
    }

    return {
      //    获取用户类别参数
      queryInfo: {
        query: '',
        pagenum: 1, //当前页数
        pagesize: 2
      },
      userList: [],
      total: 0,
      addDialogVisible:false,//控制对话话显示隐藏
      editDialogVisible:false,//控制修改用户对话框的显示与隐藏
      AddForm: { //添加用户的表单数据
          username:'',
          password:'',
          email:'qq@163.com' ,
          mobile:'17302190255'
      },
      AddFormRules: { //添加表单验证规则对象
          username:[
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 3, max:20, message: '长度在 3 到10 个字符', trigger: 'blur' }
          ],
          password:[
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 3, max:20, message: '长度在 6 到15 个字符', trigger: 'blur' }
          ],
          email:[
            { required: true, message: '请输入邮箱', trigger: 'blur' },
            { min: 3, max:20, message: '长度在 6 到15 个字符', trigger: 'blur' },
            { validator: checkEamil, trigger:'blur' }
          ],
          mobile:[
            { required: true, message: '请输入手机号码', trigger: 'blur' },
            { min: 3, max:15, message: '长度在 6 到15 个字符', trigger: 'blur' },
            { validator: checkMobile, trigger:'blur' }
          ]
      },
      editFormRules: {
         email:[
            { required: true, message: '请输入邮箱', trigger: 'blur' },
            { min: 3, max:20, message: '长度在 6 到15 个字符', trigger: 'blur' },
            { validator: checkEamil, trigger:'blur' }
          ],
          mobile:[
            { required: true, message: '请输入手机号码', trigger: 'blur' },
            { min: 3, max:15, message: '长度在 6 到15 个字符', trigger: 'blur' },
            { validator: checkMobile, trigger:'blur' }
          ]
      },
      editForm:{ //查询到的用户信息对象

      },
      removeId:'',
      setRoleDialogVisible:false,
      userInfoData:{},
      rolesList:[],
      roleValue:''
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      const res = await axios.get('users', { params: this.queryInfo })
      console.log(res)
      if (res.data.meta.status !== 200) {
          
      } else {
        this.userList = res.data.data.users
        this.total = res.data.data.total

      }
    },
    handleSizeChange(newSize){//监听pagesize改变的事件
        console.log(newSize);
        this.queryInfo.pagesize=newSize;
        this.getUserList();

    },
    handleCurrentChange(newPage){//监听页码值改变的事件
        console.log(newPage);
        this.queryInfo.pagenum=newPage;
        this.getUserList();
    },
    async userSateChange(userInfo){//监听状态 操作
       console.log(userInfo);
       const res=  await axios.put(`users/${userInfo.id}/state/${userInfo.mg_state}`);
       if (res.data.meta.status !== 200) {
           userInfo.mg_state=!userInfo.mg_state
         this.$notify.error({
          title: '提示',
          message: '更新用户信息失败'
        });

      } else {
        this.$notify({
          title: '成功',
          message: '更新用户信息成功',
          type: 'success'
        });
      }
    },
    searchUser(){
        console.log("admin");

        this.getUserList();
    },
    addDialogClosed(){ //关闭新增用户弹窗
     this.$refs.AddFormRef.resetFields();
    },
    async addUser(){ //请求添加用户
      const res = await axios.post('users', this.AddForm)
      console.log(res);
      if (res.data.meta.status !== 201) {
         this.$notify.error({
          title: '提示',
          message: '更新用户信息失败'
        });

      } else {
        this.$notify({
          title: '成功',
          message: '更新用户信息成功',
          type: 'success'
        });
      }
      //   隐藏添加用户的对话框
          this.addDialogVisible=false;
          this.getUserList();
    },
     btnAddUser(){ //点击按钮，添加用户
        this.$refs.AddFormRef.validate(validator=>{
          if (!validator) return false;
           this.addUser();
        
          
         
     });
    },
    async showEditDialog(editId){ //展示编辑用户的对话框
     console.log(editId);
     const res = await axios.get('users/'+editId);
     console.log(res);
     if (res.data.meta.status !== 200) {
         this.$notify.error({
          title: '提示',
          message: '查询用户信息失败'
        });

      } else {
        // this.$notify({
        //   title: '成功',
        //   message: '查询用户信息成功',
        //   type: 'success'
        // });
        this.editForm=res.data.data
        console.log("获取到的查询用户信息",this.editForm);
        
      }
     this.editDialogVisible=true
    },
    editDialogClosed(){ //监听修改用户对话框的关闭
     this.$refs.editFormRef.resetFields();
    },
    async editUserInfo(){ //修改用户提交
       // 发起请求
      const res = await axios.put('users/'+this.editForm.id,{
          email:this.editForm.email,
          mobile:this.editForm.mobile
      });
      console.log(res);
       if (res.data.meta.status !== 200) {
         this.$notify.error({
          title: '提示',
          message: '更新用户信息失败'
        });

      } else {
        this.$notify({
          title: '成功',
          message: '更新用户信息成功',
          type: 'success'
        });
      }
      //   隐藏添加用户的对话框
          this.editDialogVisible=false;
          this.getUserList();
  },
   btnEditUserInfo(){ //修改用户提交
    this.$refs.editFormRef.validate((validator)=>{
       console.log(validator);
       if (!validator) return false;
    //    检验通过后执行操作,发起请求
        this.editUserInfo();
     })
    },
    async btnRemoveUser(){
           // 操作点击确认删除
        const res = await axios.delete('users/'+this.removeId);
        console.log(res,"删除");
        if (res.data.meta.status === 200) {
            // 删除成功后重新调接口
           this.getUserList();
        }
    },
   async removeUser(id){ //删除用户操作
    console.log(id);
    this.removeId=id;
    console.log(this.removeId);
    
    this.$confirm('此操作将永久删除该用户信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
        // 执行删除操作
        this.btnRemoveUser();
        
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });

    },
   async setRole(userInfo){ //分配权限对话框
     this.userInfoData=userInfo
    console.log("点击分配权限对话框",this.userInfoData);
    //  在展示对话框之前，获取所有角色列表
       const res = await axios.get('roles');
      
       if (res.data.meta.status !== 200) {
          this.$message({
            type: 'success',
            message: '获取失败!'
          });
        }
        this.rolesList=res.data.data;
         console.log(this.rolesList,"角色列表");
      this.setRoleDialogVisible=true;
    },
    async saveRoleInfo(){ //点击按钮分配角色
     if (!this.roleValue) {
         return this.$message.error("请选择要分配的角色");
     }
      const res = await axios.put(`users/${this.userInfoData.id}/role`,{
          rid:this.roleValue
      });
      if (res.data.meta.status !== 200) {
          this.$message({
            type: 'success',
            message: '更新角色失败!'
          });
        }else{
            this.$message({
            type: 'success',
            message: '更新角色成功!'
          });
          this.getUserList();
          this.setRoleDialogVisible=false;
        }
    },
    setRoleDialogClosed(){ //分配角色对话的关闭事件
        this.roleValue='';
        this.userInfoData={};
    }
  }

}
</script>

<style lang="less" scoped></style>
